package org.fin.minicat.container;

import org.fin.minicat.exception.ResourceNotFoundException;
import org.fin.minicat.request.Request;
import org.fin.minicat.responce.Responce;

import java.io.File;
import java.io.FileInputStream;
import java.net.URI;

public class Engine {

  private Mapper mapper;

  public void process(Request request, Responce responce) throws Exception {
    URI uri = request.getUri();
    Wrapper wrapper = mapper.findWrapper(uri);

    // 尝试访问动态资源（Servlet）
    if (wrapper != null) {
      wrapper.getServlet().service(request, responce);
      return;
    }

    // 尝试访问静态资源
    else {
      // 获取Host对象
      Host host = mapper.findHost(uri);
      if (host == null)
        throw new ResourceNotFoundException();

      // 获取Context对象
      Context context = mapper.findContext(uri);
      if (context == null)
        throw new ResourceNotFoundException();

      // 获取静态资源相对路径
      String path = uri.getPath();
      String resourcePath = path.substring(path.indexOf('/', 1));
      // 拼装静态资源绝对路径
      String resourceLocation = host.getAppBase() + context.getContextPath() + "/web" + resourcePath;
      File file = new File(resourceLocation);
      if (file.exists() && file.isFile()) {
        FileInputStream fis = new FileInputStream(file);
        byte[] bytes = fis.readAllBytes();
        responce.setContent(bytes);
        return;
      }
    }

    // 访问不到，抛出资源找不到异常
    throw new ResourceNotFoundException();
  }

  public Mapper getMapper() {
    return mapper;
  }

  public void setMapper(Mapper mapper) {
    this.mapper = mapper;
  }
}
